package com.itboye.eweilisten.base;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.v4.app.FragmentActivity;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.alipay.android.phone.mrpc.core.NetworkUtils;
import com.itboye.eweilisten.R;
import com.itboye.eweilisten.app.MyApplication;
import com.itboye.eweilisten.util.loadingutil.LoadingDialog;
import com.itboye.eweilisten.util.loadingutil.MAlert;
import com.itboye.eweilisten.util.network.NetState;
import com.itboye.eweilisten.util.network.NetWorkUtil;
import com.itboye.eweilisten.volley.ResultEntity;
import com.umeng.analytics.MobclickAgent;

import java.lang.reflect.Field;
import java.lang.reflect.Method;


/**
 * 继承自该类的Activity不需要使用findViewById(),只需要把控件声明称类内全局的，</br>并且和activity对应的布局中的id的名字相同，这样setContentView后就可以直接使用控件了，</br>
 * 同时不需要为控件设置clickListener， 直接在类上implements onClickListener,</br>
 * 并在activity中 重写onClick()方法，当点击控件时即可自动调用onClick()方法
 * 
 * </br>参考 
 * 沉浸式状态栏 ，设置状态栏颜色使用setStatusBarColor，参数为颜色资源id，默认为橙色状态栏
 * @author Young
 *
 *
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB) public class BaseActivity extends FragmentActivity implements View.OnClickListener {

	private View statusBar;

	private LinearLayout container;
	LoadingDialog progressDialog=null;
	/**
	 * 是否开启  右划关闭activity 手势，默认开启
	 */
	private boolean isGestureOpen=true;
	@SuppressLint("InlinedApi")
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		MyApplication.getInstance().addActivity(this);
		setVolumeControlStream(AudioManager.STREAM_MUSIC);
		progressDialog=new LoadingDialog();
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			Window window = getWindow();
			// Translucent status bar
			window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

			statusBar = new View(this);
			ViewGroup.LayoutParams param = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
					getStatusBarHeight());
			statusBar.setLayoutParams(param);
			setStatusBarColor(R.color.main_color);

			  container =new ViewContainer(getApplicationContext());
			container.setOrientation(LinearLayout.VERTICAL);
			container.addView(statusBar);

			//App.getInstance().addActivity(this);

		}

//		PushAgent.getInstance(getApplicationContext()).onAppStart();
	}

	public static final String EVENT_TYPE_UNKNOWN = BaseActivity.class
			.getName() + "_unknown";
	/**
	 * //     * @param data
	 *
	 * @return 2016-4-23 hebidu
	 */
	public ResultEntity handlerError(Object data) {
		ResultEntity result = (ResultEntity) data;
		if (result == null) {
			result = new ResultEntity("-1", "数据格式错误!~", data);
			return result;
		}

		if (result.hasError()) {
			MAlert.alert(result.getMsg(), Gravity.TOP);
			result.setEventType(EVENT_TYPE_UNKNOWN);
			return result;
		}

		return result;
	}

	@Override
	public void startActivityForResult(Intent intent, int requestCode) {
		
		super.startActivityForResult(intent, requestCode);
//		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
//			overridePendingTransition(R.anim.anim_enter_open_activity, R.anim.anim_exit_open_activity);
//		}
	}

	
	@SuppressLint("NewApi")
	public void startActivityForResult(Intent intent, int requestCode, Bundle options) {
		super.startActivityForResult(intent, requestCode, options);
//		overridePendingTransition(R.anim.anim_enter_open_activity, R.anim.anim_exit_open_activity);
	}
	
	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();
//		overridePendingTransition(R.anim.anim_enter_finish_activity, R.anim.anim_exit_finish_activity);
	}
	/**
	 * 设置状态栏颜色，
	 * 
	 * @param color  颜色资源id， 如 R.color.orange</br>
	 *            0 黑色
	 */
	protected void setStatusBarColor(int color) {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			if (color == 0) {
				statusBar.setBackgroundColor(Color.BLACK);
			} else {
				statusBar.setBackgroundColor(getResources().getColor(color));
			}

		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		MobclickAgent.onResume(this);
	}
	
	public void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
		}
	
	/**
	 * 显示进度对话框,带有消息 flag 是否可以取消
	 */
	@SuppressLint("NewApi")
	public void showProgressDialog(String message, boolean flag) {
		if (progressDialog == null)
			return;
		setProgressDialogMessage(message);
		
		progressDialog.show(getFragmentManager(), message);
		progressDialog.setCancelable(flag);

	}
	
	/**
	 * 设置进度对话框消息
	 * 
	 * @param message
	 */
	public void setProgressDialogMessage(String message) {
		progressDialog.setMsg(message);
	}

	/**
	 * 关闭进度对话框
	 */
	@SuppressLint("NewApi")
	public void closeProgressDialog() {
		if (progressDialog == null)
			return;
		if (progressDialog.getDialog().isShowing()) {
			progressDialog.dismiss();
		}
	}
	
	@Override
	public void setContentView(@LayoutRes int layoutResID) {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

			LayoutInflater.from(this).inflate(layoutResID, container, true);
			setContentView(container);

		}else{
			super.setContentView(layoutResID);
		}
		smartInject();
//		FrameLayout container = new FrameLayout(this);
//		// 在用户布局外面嵌套一个FrameLayout，防止用户布局中根控件的margin失效
//		LayoutInflater.from(this).inflate(layoutResID, container, true);
//		setContentView(container);

	}

	
//	@Override
//	public void setContentView(View view) {
//
//		container.addView(view);
//
//		super.setContentView(container);
//
//		adjustContentMargin(view);
//		((ViewGroup) getWindow().getDecorView()).addView(statusBar);
//		smartInject();
//	}
//
//	private void adjustContentMargin(View view) {
//		ViewGroup.LayoutParams param = view.getLayoutParams();
//
//		ViewGroup.MarginLayoutParams margParam;
//		if (param instanceof ViewGroup.MarginLayoutParams) {
//
//			margParam = (ViewGroup.MarginLayoutParams) param;
//			margParam.setMargins(margParam.leftMargin, margParam.topMargin + getStatusBarHeight(),
//					margParam.rightMargin, margParam.bottomMargin);
//		} else {
//
//			margParam = new ViewGroup.MarginLayoutParams(param);
//			margParam.setMargins(0, getStatusBarHeight(), 0, 0);
//		}
//		view.setLayoutParams(margParam);
//	}

	protected int getStatusBarHeight() {
		int result = 0;
		int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
		if (resourceId > 0) {
			result = getResources().getDimensionPixelSize(resourceId);
		}
		return result;
	}

	/**
	 * 设置是否允许屏幕左侧 快速 右划关闭activity，默认允许
	 * @param b
	 */
	protected void isGestureSensitive(boolean b) {
		isGestureOpen=b;
	}
	private void smartInject() {
		
		try {
			Class<? extends Activity> clz = getClass();
			
			while (clz!=BaseActivity.class) {
				 
				Field[] fs = clz.getDeclaredFields();
				Resources res = getResources();
				String packageName = getPackageName();
				for (Field field : fs) {
					if (!View.class.isAssignableFrom(field.getType())) {
						continue;
					}
					int viewId = res.getIdentifier(field.getName(), "id", packageName);
					if (viewId == 0)
						continue;
					field.setAccessible(true);
					try {
						View v = findViewById(viewId);
						field.set(this, v);
						Class<?> c = field.getType();
						Method m = c.getMethod("setOnClickListener", View.OnClickListener.class);
						m.invoke(v, this);
					} catch (Throwable e) {
					}
					field.setAccessible(false);

				}
				 
				clz=(Class<? extends Activity>) clz.getSuperclass();
				
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	 

	}

	@Override
	public void onClick(View view) {

	}
	/**
	 *  隐藏键盘
	 */
	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		if(ev.getAction()==MotionEvent.ACTION_DOWN){
			View v=getCurrentFocus();
			if(isShouldHideInput(v,ev)){
				InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
				if  (imm != null) {
					imm.hideSoftInputFromWindow(v.getWindowToken(),0);
				}
			}

			return super.dispatchTouchEvent(ev);}
		if(getWindow().superDispatchTouchEvent(ev)){
			return true;
		}
		return onTouchEvent(ev);
	}

	public boolean isShouldHideInput(View v, MotionEvent ev) {
		if(v!=null&&(v instanceof EditText)){
			int[] leftTop = {0,0};
			//获取输入框当前的location位置  
			v.getLocationInWindow(leftTop);
			int left= leftTop[0];
			int top= leftTop[1];
			int bottom = top + v.getHeight();
			int right = left + v.getWidth();
			if(ev.getX()>left&&ev.getX()<right
					&& ev.getY()>top && ev.getY()<bottom){
				// 点击的是输入框区域，保留点击EditText的事件  
				return false;
			}else{
				return true;
			}
		}
		return false;

	}



	/**
	 * 屏幕左侧右划返回容器 , 
	 * @author Young
	 *
	 */
	private class ViewContainer extends LinearLayout{

		private int leftMargin;
		private VelocityTracker tracker;
		private float startX;
		private float startY;
		public ViewContainer(Context context) {
			super(context);
//			leftMargin= DensityUtil.dip2px(35);
			
		}
		
		@Override
		public boolean dispatchTouchEvent(MotionEvent ev) {
			if (isGestureOpen==false) {
				return super.dispatchTouchEvent(ev);
			}
			switch (ev.getAction()) {
			case MotionEvent.ACTION_CANCEL:
			case MotionEvent.ACTION_UP:
				//当满足下面条件时 视为 右划关闭手势  
				//起始按压位置x坐标小与leftMargin&& 向右滑动                       &&           向右滑动距离    >   竖直方向距离 
				if (startX<leftMargin&& ev.getRawX()>startX && ev.getRawX()-startX>Math.abs(ev.getRawY()-startY) ) {
					//速度大于2500时关闭activity
					tracker.computeCurrentVelocity(1000);
					 if (tracker.getXVelocity()>2500) {
						finish();
					}
					
				}
				 
				tracker.recycle();
				break;

			case MotionEvent.ACTION_DOWN:
				startX=ev.getRawX();
				startY=ev.getRawY();
				tracker=VelocityTracker.obtain();
				tracker.addMovement(ev);
				break;
			case MotionEvent.ACTION_MOVE:
				tracker.addMovement(ev);
				break;
			}
			
			 
			return super.dispatchTouchEvent(ev);
		}
		
		@Override
		public boolean onTouchEvent(MotionEvent event) {
			if (isGestureOpen==false) {
				return super.onTouchEvent(event);
			}
			return true;
		}
		
	}

}
